/* eslint-disable max-len */
import { useContext } from 'react';

import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { useWindowSize } from 'usehooks-ts';

const isMobile = () => {
  const toMatch = [/Android/i, /webOS/i, /iPhone/i, /iPad/i, /iPod/i, /BlackBerry/i, /Windows Phone/i];

  return toMatch.some((toMatchItem) => navigator.userAgent.match(toMatchItem));
};

export const useShare = (args: ShareData | void) => {
  const data = args || {};
  const { openModal } = useContext(ModalContext);
  const { width } = useWindowSize();
  return async () => {
    if (width > 767 || !isMobile()) {
      openModal(Modals.ShareModal);
      return;
    }

    const preparedData: ShareData = {
      ...data,
      // text: data?.text || 'companyName', // hide so browser could pick it from meta
      // Title: data?.Title || 'companyName', // hide so browser could pick it from meta
      url: data?.url || window.location.href,
    };

    if (navigator?.share) {
      await navigator.share(preparedData);
      return;
    }
    openModal(Modals.ShareModal);
  };
};
